In [42]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
In [43]:
%matplotlib inline
In [44]:
def medianFilter( data, windowLength ):
if (windowLength < len(data)and data.ndim == 1):
tempret = np.zeros(len(data)-windowLength+1)
if windowLength % 2 ==0:
for c in range(0, len(tempret)):
tempret[c] = np.median( data[ c : c + windowLength +1 ] )
return tempret
else:
for c in range(0, len(tempret)):
tempret[c] = np.median( data[ c : c + windowLength ] )
return tempret
else:
raise ValueError("windowLength must be smaller than len(data) and data must be a 1D array")
In [45]:
def ErrorRate(signal, datafiltered,wavenumber, windowLength):
#calculate the difference between the sine wave and the filtered wave
errorrate = signal-datafiltered
#creating a list and save the error rate (y) and window length (x) in it
error = []
errorrate = np.abs(errorrate)
error.append([wavenumber ,np.mean(errorrate)])
#zip the error list
error = zip(*error)
return error
In [46]:
def Errorplot( wavenumber, windowLength ):
data = np.fromfunction( lambda x: np.sin((x-windowLength / 2)/128 * 2 * np.pi * wavenumber), (128 + windowLength / 2, ) )
noise = np.random.normal(0,0.5,(128 + windowLength / 2))
signal = data + noise
datafiltered = medianFilter(signal, windowLength)
signal = signal[ windowLength / 2 : - windowLength ]
datafiltered = datafiltered[ : len(signal) ]
error = ErrorRate(signal,datafiltered,wavenumber,windowLength)
plt.axis([0, x + 1, 0, 1])
plt.xlabel('Wave number', fontsize = 20)
plt.ylabel('Error rate', fontsize = 20)
plt.scatter(*error)
In [50]:
fig = plt.figure()
for x in range (0,50):
Errorplot(x,5)
In [48]:
pp = PdfPages( 'Error of the median filtered sine waves with white noise and different wave numbers.pdf')
pp.savefig(fig)
pp.close()